package cn.iocoder.devlop.module.annual.report.baseinfo.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.devlop.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.devlop.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.devlop.module.annual.report.alterstockinfo.dal.AlterstockinfoMapper;
import cn.iocoder.devlop.module.annual.report.alterstockinfo.dal.dataobject.AlterstockinfoDO;
import cn.iocoder.devlop.module.annual.report.baseinfo.controller.vo.*;
import cn.iocoder.devlop.module.annual.report.baseinfo.convert.BaseinfoConvert;
import cn.iocoder.devlop.module.annual.report.baseinfo.dal.BaseinfoMapper;
import cn.iocoder.devlop.module.annual.report.baseinfo.dal.dataobject.BaseinfoDO;
import cn.iocoder.devlop.module.annual.report.common.service.EnttypeAntypeService;
import cn.iocoder.devlop.module.annual.report.common.service.EnttypeEntclassifyService;
import cn.iocoder.devlop.module.annual.report.enums.ChangeInfoNotificationEnum;
import cn.iocoder.devlop.module.annual.report.forguaranteeinfo.dal.ForguaranteeinfoMapper;
import cn.iocoder.devlop.module.annual.report.forguaranteeinfo.dal.dataobject.ForguaranteeinfoDO;
import cn.iocoder.devlop.module.annual.report.forinvestment.dal.ForinvestmentMapper;
import cn.iocoder.devlop.module.annual.report.forinvestment.dal.dataobject.ForinvestmentDO;
import cn.iocoder.devlop.module.annual.report.impconf.dal.dataobject.ImpConfDO;
import cn.iocoder.devlop.module.annual.report.impconf.service.ImpConfService;
import cn.iocoder.devlop.module.annual.report.marpripinfo.dal.dataobject.MarpripinfoDO;
import cn.iocoder.devlop.module.annual.report.marpripinfo.service.MarpripinfoService;
import cn.iocoder.devlop.module.annual.report.overduepay.dal.OverduepayMapper;
import cn.iocoder.devlop.module.annual.report.overduepay.dal.dataobject.OverduepayDO;
import cn.iocoder.devlop.module.annual.report.pushconf.dal.dataobject.PushConfDO;
import cn.iocoder.devlop.module.annual.report.pushconf.service.PushConfService;
import cn.iocoder.devlop.module.annual.report.supbaseinfo.controller.vo.SupBaseinfoOverwriteVO;
import cn.iocoder.devlop.module.annual.report.supbaseinfo.dal.dataobject.SupBaseinfoDO;
import cn.iocoder.devlop.module.annual.report.supbaseinfo.service.SupBaseinfoService;
import cn.iocoder.devlop.module.annual.report.utils.IdGenerateUtil;
import cn.iocoder.devlop.module.annual.report.utils.ObjectComparisonUtil;
import cn.iocoder.devlop.module.annual.report.utils.ReportYearHelper;
import cn.iocoder.devlop.module.annual.report.websiteinfo.dal.WebsiteinfoMapper;
import cn.iocoder.devlop.module.annual.report.websiteinfo.dal.dataobject.WebsiteinfoDO;
import cn.iocoder.devlop.module.annual.report.wsbaseinfo.service.WsBaseinfoService;
import cn.iocoder.devlop.module.infra.util.ConfigUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;

import static cn.iocoder.devlop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.devlop.module.annual.report.enums.ErrorCodeConstants.BASEINFO_NOT_EXISTS;


/**
 * 年报基本信息表(基本信息，资产状况，党建信息) Service 实现类
 *
 * @author sunhao
 */
@Service
@Validated
@RequiredArgsConstructor
public class BaseinfoServiceImpl implements BaseinfoService {

    private final BaseinfoMapper baseinfoMapper;

    private final MarpripinfoService marpripinfoService;

    private final SupBaseinfoService supBaseinfoService;

    private final PushConfService pushConfService;

    private final ImpConfService impConfService;

    private final WebsiteinfoMapper websiteinfoMapper;

    private final WsBaseinfoService wsBaseinfoService;

    private final EnttypeAntypeService enttypeAntypeService;

    private final EnttypeEntclassifyService enttypeEntclassifyService;

    private final ForguaranteeinfoMapper forguaranteeinfoMapper;

    private final ForinvestmentMapper forinvestmentMapper;

    private final AlterstockinfoMapper alterstockinfoMapper;

    private final OverduepayMapper overduepayMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    @Transactional
    public void updateBaseinfo(BaseinfoUpdateReqVO baseinfoUpdateReqVO) {
        String ancheid = IdGenerateUtil.getAncheid(baseinfoUpdateReqVO.getRegno(), baseinfoUpdateReqVO.getAncheyear());
        ReportYearHelper.setYear(NumberUtil.parseInt(baseinfoUpdateReqVO.getAncheyear()));
        // 先查库
        BaseinfoDO oldBaseinfoDO = baseinfoMapper.selectByRegnoAndAncheyear(baseinfoUpdateReqVO.getRegno(), baseinfoUpdateReqVO.getAncheyear());
        if (null == oldBaseinfoDO) {
            initBaseinfo(baseinfoUpdateReqVO.getRegno(), baseinfoUpdateReqVO.getAncheyear());
        }else {
            // 如果是已提交的进行修改表的数据增加
            if (StrUtil.equals(oldBaseinfoDO.getState(),"02") || StrUtil.equals(oldBaseinfoDO.getState(),"03")) {
                BaseinfoUpdateReqVO oldBean = BeanUtil.toBean(oldBaseinfoDO, BaseinfoUpdateReqVO.class);
                ObjectComparisonUtil.compareObjects(oldBean,baseinfoUpdateReqVO,ancheid);
            }
        }
        // vo转do,进行修改
        BaseinfoDO baseinfo = BaseinfoConvert.INSTANCE.convert(baseinfoUpdateReqVO);
        baseinfo.setAncheid(ancheid);
        // 修改时需要设置的字段
        baseinfo.setLastupdatetime(LocalDateTimeUtil.now());
        SupBaseinfoOverwriteVO supBaseinfoOverwriteVO = new SupBaseinfoOverwriteVO();
        supBaseinfoOverwriteVO.setRegno(baseinfoUpdateReqVO.getRegno());
        supBaseinfoOverwriteVO.setAncheyear(baseinfoUpdateReqVO.getAncheyear());
        SupBaseinfoDO supBaseinfoDO = supBaseinfoService.getSupBaseinfo(baseinfoUpdateReqVO.getRegno(), baseinfoUpdateReqVO.getAncheyear());
        if (ObjectUtil.isNull(supBaseinfoDO)){
            supBaseinfoDO = new SupBaseinfoDO();
        }
        // 可以尝试用beanUtil来做
        supBaseinfoDO.setAncheid(ancheid);
        supBaseinfoDO.setDependententname(baseinfoUpdateReqVO.getDependententname());
        supBaseinfoDO.setDepuniscid(baseinfoUpdateReqVO.getDepuniscid());
        // 获取公司信息
        MarpripinfoDO marpripinfo = marpripinfoService.getMarpripinfo(baseinfoUpdateReqVO.getRegno());
        supBaseinfoDO.setEntclassify(enttypeEntclassifyService.getEntclassify(marpripinfo.getEnttype()));
        supBaseinfoDO.setMainbusiact(baseinfoUpdateReqVO.getMainbusiact());
        supBaseinfoDO.setHoldingsmsg(baseinfoUpdateReqVO.getHoldingsmsg());
        supBaseinfoDO.setHoldingsmsgCn(baseinfoUpdateReqVO.getHoldingsmsgCn());
        supBaseinfoDO.setHoldingsmsgdis(baseinfoUpdateReqVO.getHoldingsmsgdis());
        if (marpripinfo.getEnttype().equals("9100")) {
            supBaseinfoDO.setAddr(baseinfoUpdateReqVO.getAddr());
        }
        List<SupBaseinfoDO> supBaseinfoDOS = new ArrayList<>();
        supBaseinfoDOS.add(supBaseinfoDO);
        supBaseinfoOverwriteVO.setSupBaseinfoList(supBaseinfoDOS);
        supBaseinfoService.overwriteSupBaseinfo(supBaseinfoOverwriteVO);
        baseinfoMapper.updateById(baseinfo);
        updateState(baseinfoUpdateReqVO.getRegno(), baseinfoUpdateReqVO.getAncheyear());
    }


    public Boolean validateBaseinfoExists(String regno, String ancheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        if (null == baseinfoMapper.selectByRegnoAndAncheyear(regno, ancheyear)) {
            return false;
        }
        return true;
    }

    @Override
    public BaseinfoDO getBaseinfo(String regno, String ancheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        return baseinfoMapper.selectByRegnoAndAncheyear(regno, ancheyear);
    }


    @Override
    public List<CompletionCheckVO> getBaseinfoList(String regno, String uniscid) {
        // 获取该企业已经年报的信息
        List<String> tables = ChangeInfoNotificationEnum.Target.findTables("t_baseinfo");
        List<CompletionCheckVO> checkVOS = baseinfoMapper.selectListByInfo(regno, uniscid, tables);
        ArrayList<CompletionCheckVO> returnList = new ArrayList<>();
        Dict checkMap = Dict.create();
        // 将list转为map,ancheyear为key，对象本身为value
        if (CollUtil.isNotEmpty(checkVOS)){
            for (CompletionCheckVO checkVO:checkVOS){
                checkMap.set(checkVO.getAncheyear(),checkVO);
            }
        }
        // 获取该企业哪些年应该年报
        MarpripinfoDO marpripinfo = marpripinfoService.getMarpripinfo(regno);
        LocalDateTime estDate = marpripinfo.getEstdate();
        int yearEst = estDate.getYear();
        int yearNow = LocalDateTime.now().getYear();
        for (int i = yearEst; i <yearNow; i++) {
            Object o = checkMap.get(String.valueOf(i));
            if (ObjUtil.isNotEmpty(o)) {
                returnList.add((CompletionCheckVO)o);
            }else {
                CompletionCheckVO checkVO = new CompletionCheckVO();
                checkVO.setAncheyear(String.valueOf(i));
                checkVO.setUniscid(marpripinfo.getUniscid());
                checkVO.setRegno(marpripinfo.getRegno());
                returnList.add(checkVO);
            }
        }
        return returnList;
    }

    @Override
    public BaseinfoDO submit(BaseinfoVO baseinfoVO) {
        ReportYearHelper.setYear(NumberUtil.parseInt(baseinfoVO.getAncheyear()));
        BaseinfoDO baseinfoDO = baseinfoMapper.selectByRegnoAndAncheyear(baseinfoVO.getRegno(), baseinfoVO.getAncheyear());
        if (Objects.isNull(baseinfoDO)) {
            // 报错
            throw exception(BASEINFO_NOT_EXISTS);
        }
        baseinfoDO.setState("02");
        baseinfoDO.setAnchedate(LocalDateTime.now());
        baseinfoDO.setLastupdatetime(LocalDateTime.now());
        baseinfoMapper.updateById(baseinfoDO);
        pushToStandardLibrary(baseinfoDO);
        return baseinfoDO;
    }


    public void deleteBaseinfo(String regno, String ancheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        String ancheid = IdGenerateUtil.getAncheid(regno, ancheyear);
        baseinfoMapper.deleteById(ancheid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Boolean> impData(String regno, String impAncheyear, String targetAncheyear, String enttype) {

        // 将基础信息表和补充信息表进行单独处理
        // 进行删除，删除完成后进行添加
        deleteBaseinfo(regno, targetAncheyear);
        // 基础信息表
        BaseinfoDO impBaseinfo = getImpBaseInfo(regno, impAncheyear);
        LocalDateTime now = LocalDateTime.now();
        impBaseinfo.setAncheid(IdGenerateUtil.getAncheid(impBaseinfo.getRegno(), targetAncheyear));
        impBaseinfo.setAncheyear(targetAncheyear);
        impBaseinfo.setCreatetime(now);
        impBaseinfo.setLastupdatetime(now);
        impBaseinfo.setState("00");
        ReportYearHelper.setYear(NumberUtil.parseInt(targetAncheyear));
        baseinfoMapper.insert(impBaseinfo);
        // 补充信息表
        List<SupBaseinfoDO> impSupBaseinfoList = supBaseinfoService.getSupBaseinfoList(regno, impAncheyear);
        SupBaseinfoOverwriteVO supOverwriteVO = new SupBaseinfoOverwriteVO();
        supOverwriteVO.setRegno(regno);
        supOverwriteVO.setAncheyear(targetAncheyear);
        supOverwriteVO.setSupBaseinfoList(impSupBaseinfoList);
        supBaseinfoService.overwriteSupBaseinfo(supOverwriteVO);
        // 外商
//        WsBaseinfoDO wsBaseinfoDO = wsBaseinfoService.getWsBaseinfoAll(IdGenerateUtil.getAncheid(regno, impAncheyear));
//        if (ObjUtil.isNotNull(wsBaseinfoDO)) {
//            wsBaseinfoDO.setAncheid(IdGenerateUtil.getAncheid(regno, targetAncheyear));
//            wsBaseinfoDO.setAnchedate(LocalDateTime.now());
//            wsBaseinfoDO.setAncheyear(targetAncheyear);
//            wsBaseinfoService.updateBaseinfoAll(wsBaseinfoDO);
//        }
        // 其他表统一处理
        String targetAncheid = IdGenerateUtil.getAncheid(regno, targetAncheyear);
        String impAncheid = IdGenerateUtil.getAncheid(regno, impAncheyear);
        List<ImpConfDO> impConfDOS = impConfService.selectByEnttype(enttype);
        StrBuilder deleteSqlBuilder = StrUtil.strBuilder();
        StrBuilder insertSqlBuilder = StrUtil.strBuilder();
        for (ImpConfDO impConf : impConfDOS) {
            String deleteTemp = "DELETE FROM {} WHERE ancheid = {};";
            String insertTemp = "INSERT INTO {}  ({}) SELECT  {} FROM {} WHERE ancheid = {};";
            String targetTable = StrUtil.format(impConf.getTargetTable(), ReportYearHelper.getStartYear(NumberUtil.parseInt(targetAncheyear)));
            String targetField = impConf.getTargetField();
            String sourceField = StrUtil.format(impConf.getSourceField(), targetAncheid);
            String sourceTable = StrUtil.format(impConf.getSourceTable(), ReportYearHelper.getStartYear(NumberUtil.parseInt(impAncheyear)));
            String deleteSql = StrUtil.format(deleteTemp, targetTable, targetAncheid);
            String insertSql = StrUtil.format(insertTemp, targetTable, targetField, sourceField, sourceTable, impAncheid);
            deleteSqlBuilder.append(deleteSql);
            insertSqlBuilder.append(insertSql);
//            jdbcTemplate.update(deleteSql, targetAncheid);
//            jdbcTemplate.update(insertSql, impAncheid);
        }
        jdbcTemplate.update(deleteSqlBuilder.toString());
        jdbcTemplate.update(insertSqlBuilder.toString());
        return getFillingResults(regno, targetAncheyear, enttype);
    }

    @Override
    public void initBaseinfo(String regno, String ancheyear) {
        MarpripinfoDO marpripinfo = marpripinfoService.getMarpripinfo(regno);
        BaseinfoDO baseinfoDO = new BaseinfoDO();
        baseinfoDO.setAncheid(IdGenerateUtil.getAncheid(regno, ancheyear));
        baseinfoDO.setPripid(marpripinfo.getId());
        baseinfoDO.setAncheyear(ancheyear);
        baseinfoDO.setRegno(regno);
        baseinfoDO.setUniscid(marpripinfo.getUniscid());
        if (marpripinfo.getEnttype().equals("9600")) {
            baseinfoDO.setTraname(marpripinfo.getEntname());
            baseinfoDO.setName(marpripinfo.getLerep());
        } else if (marpripinfo.getEnttype().equals("9100")) {
            baseinfoDO.setFarspeartname(marpripinfo.getEntname());
        } else {
            baseinfoDO.setEntname(marpripinfo.getEntname());
        }
        baseinfoDO.setEnttype(marpripinfo.getEnttype());
        baseinfoDO.setLastupdatetime(LocalDateTime.now());
        baseinfoDO.setCreatetime(LocalDateTime.now());
        baseinfoDO.setEntclassify(enttypeEntclassifyService.getEntclassify(marpripinfo.getEnttype()));
        baseinfoDO.setAnnrepform("1");
        baseinfoDO.setState("01");
        baseinfoDO.setSourcetype("3");
        baseinfoDO.setPubstate("1");
        baseinfoDO.setUserid(StrUtil.toStringOrNull(SecurityFrameworkUtils.getLoginUserId()));
        baseinfoDO.setBusst(marpripinfo.getOpstate());
        baseinfoDO.setBusstCn(marpripinfo.getOpstatename());
        baseinfoDO.setAntype(enttypeAntypeService.getAntype(marpripinfo.getEnttype()));
        baseinfoDO.setEncryptionmessage(null);
        baseinfoDO.setAkbean(null);
        baseinfoDO.setLasttab(null);
        baseinfoMapper.insert(baseinfoDO);
    }

    @Override
    @Transactional
    public void updateEmpnum(EmpnumUpdateVO empnumUpdateVO) {
        ReportYearHelper.setYear(NumberUtil.parseInt(empnumUpdateVO.getAncheyear()));
        // 先判断是否存在,存在的话进行修改,不存在进行初始化
        if (!validateBaseinfoExists(empnumUpdateVO.getRegno(), empnumUpdateVO.getAncheyear())) {
            initBaseinfo(empnumUpdateVO.getRegno(), empnumUpdateVO.getAncheyear());
        }
        // vo转do,进行修改
        BaseinfoDO baseinfo = BaseinfoConvert.INSTANCE.convert(empnumUpdateVO);
        baseinfo.setAncheid(IdGenerateUtil.getAncheid(empnumUpdateVO.getRegno(), empnumUpdateVO.getAncheyear()));
        // 修改时需要设置的字段
        baseinfo.setLastupdatetime(LocalDateTimeUtil.now());

        MarpripinfoDO marpripinfo = marpripinfoService.getMarpripinfo(empnumUpdateVO.getRegno());
        // 修改补充信息表
        SupBaseinfoOverwriteVO supBaseinfoOverwriteVO = new SupBaseinfoOverwriteVO();
        supBaseinfoOverwriteVO.setRegno(empnumUpdateVO.getRegno());
        supBaseinfoOverwriteVO.setAncheyear(empnumUpdateVO.getAncheyear());
        SupBaseinfoDO supBaseinfoDO = supBaseinfoService.getSupBaseinfo(empnumUpdateVO.getRegno(), empnumUpdateVO.getAncheyear());
        if (ObjectUtil.isNull(supBaseinfoDO)){
            supBaseinfoDO = new SupBaseinfoDO();
        }
        supBaseinfoDO.setAncheid(IdGenerateUtil.getAncheid(empnumUpdateVO.getRegno(), empnumUpdateVO.getAncheyear()));
        supBaseinfoDO.setWomempnumdis(empnumUpdateVO.getWomempnumdis());
        supBaseinfoDO.setWomempnum(empnumUpdateVO.getWomempnum());
        if (marpripinfo.getEnttype().equals("9100")) {
            supBaseinfoDO.setEmpnum(empnumUpdateVO.getEmpnum());
            supBaseinfoDO.setEmpnumdis(empnumUpdateVO.getEmpnumdis());
        }
        List<SupBaseinfoDO> supBaseinfoDOS = new ArrayList<>();
        supBaseinfoDOS.add(supBaseinfoDO);
        supBaseinfoOverwriteVO.setSupBaseinfoList(supBaseinfoDOS);
        supBaseinfoService.overwriteSupBaseinfo(supBaseinfoOverwriteVO);
        baseinfoMapper.updateById(baseinfo);
        updateState(empnumUpdateVO.getRegno(), empnumUpdateVO.getAncheyear());
    }

    @Override
    public void updatePartybuilding(PartybuildingUpdateVO partybuildingUpdateVO) {
        ReportYearHelper.setYear(NumberUtil.parseInt(partybuildingUpdateVO.getAncheyear()));
        // 先判断是否存在,存在的话进行修改,不存在进行初始化
        if (!validateBaseinfoExists(partybuildingUpdateVO.getRegno(), partybuildingUpdateVO.getAncheyear())) {
            initBaseinfo(partybuildingUpdateVO.getRegno(), partybuildingUpdateVO.getAncheyear());
        }
        // vo转do,进行修改
        BaseinfoDO baseinfo = BaseinfoConvert.INSTANCE.convert(partybuildingUpdateVO);
        baseinfo.setAncheid(IdGenerateUtil.getAncheid(partybuildingUpdateVO.getRegno(), partybuildingUpdateVO.getAncheyear()));
        // 修改时需要设置的字段
        baseinfo.setLastupdatetime(LocalDateTimeUtil.now());
        baseinfo.setPartybuilding("1");
        if(StrUtil.equals("4",partybuildingUpdateVO.getParins())){
            baseinfo.setPartybuilding("2");
        }
        baseinfoMapper.updateById(baseinfo);
        updateState(partybuildingUpdateVO.getRegno(), partybuildingUpdateVO.getAncheyear());
    }

    @Override
    public void updateAssetinfo(AssetinfoUpdateVO assetinfoUpdateVO) {
        ReportYearHelper.setYear(NumberUtil.parseInt(assetinfoUpdateVO.getAncheyear()));
        // 先判断是否存在,存在的话进行修改,不存在进行初始化
        if (!validateBaseinfoExists(assetinfoUpdateVO.getRegno(), assetinfoUpdateVO.getAncheyear())) {
            initBaseinfo(assetinfoUpdateVO.getRegno(), assetinfoUpdateVO.getAncheyear());
        }
        // vo转do,进行修改
        BaseinfoDO baseinfo = BaseinfoConvert.INSTANCE.convert(assetinfoUpdateVO);
        baseinfo.setAncheid(IdGenerateUtil.getAncheid(assetinfoUpdateVO.getRegno(), assetinfoUpdateVO.getAncheyear()));
        // 修改时需要设置的字段
        baseinfo.setLastupdatetime(LocalDateTimeUtil.now());
        baseinfoMapper.updateById(baseinfo);
        updateState(assetinfoUpdateVO.getRegno(), assetinfoUpdateVO.getAncheyear());
    }

    @Override
    public void baseinfoUpdate(BaseinfoDO baseinfo) {
        baseinfoMapper.updateById(baseinfo);
    }

    @Override
    public BaseinfoUpdateReqVO getBaseinfoForApp(String regno, String ancheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        BaseinfoDO baseinfoDO = baseinfoMapper.selectByRegnoAndAncheyear(regno, ancheyear);
        if (ObjectUtil.isNull(baseinfoDO)){
            return null;
        }
        BaseinfoUpdateReqVO baseinfoUpdateReqVO = BeanUtil.copyProperties(baseinfoDO, BaseinfoUpdateReqVO.class);
        List<SupBaseinfoDO> supBaseinfoList = supBaseinfoService.getSupBaseinfoList(regno, ancheyear);
        if (CollUtil.isNotEmpty(supBaseinfoList)) {
            BeanUtil.copyProperties(supBaseinfoList.get(0), baseinfoUpdateReqVO, true);
        }
        if (!StrUtil.equals(baseinfoDO.getEntclassify(),"9100")){
            baseinfoUpdateReqVO.setAddr(baseinfoDO.getAddr());
        }
        return baseinfoUpdateReqVO;
    }

    @Override
    public EmpnumUpdateVO getEmpnum(String regno, String ancheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        BaseinfoDO baseinfoDO = baseinfoMapper.selectByRegnoAndAncheyear(regno, ancheyear);
        if(ObjUtil.isEmpty(baseinfoDO)){
            return null;
        }
        EmpnumUpdateVO empnumUpdateVO = BeanUtil.copyProperties(baseinfoDO, EmpnumUpdateVO.class);
        List<SupBaseinfoDO> supBaseinfoList = supBaseinfoService.getSupBaseinfoList(regno, ancheyear);
        if (CollUtil.isNotEmpty(supBaseinfoList)) {
            BeanUtil.copyProperties(supBaseinfoList.get(0), empnumUpdateVO, true);
        }
        if (!StrUtil.equals(baseinfoDO.getEntclassify(),"9100")){
            empnumUpdateVO.setEmpnum(baseinfoDO.getEmpnum());
            empnumUpdateVO.setEmpnumdis(baseinfoDO.getEmpnumdis());
        }
        return empnumUpdateVO;
    }

    @Override
    public PartybuildingUpdateVO getPartybuilding(String regno, String ancheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        BaseinfoDO baseinfoDO = baseinfoMapper.selectByRegnoAndAncheyear(regno, ancheyear);
        return BeanUtil.copyProperties(baseinfoDO, PartybuildingUpdateVO.class);
    }

    @Override
    public AssetinfoUpdateVO getAssetinfo(String regno, String ancheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        BaseinfoDO baseinfoDO = baseinfoMapper.selectByRegnoAndAncheyear(regno, ancheyear);
        return BeanUtil.copyProperties(baseinfoDO, AssetinfoUpdateVO.class);
    }



    private void pushToStandardLibrary(BaseinfoDO baseinfo) {
        List<PushConfDO> pushConfList = pushConfService.getPushConfList(baseinfo.getEntclassify());
        StrBuilder deleteBuilder = StrUtil.strBuilder();
        StrBuilder insertBuilder = StrUtil.strBuilder();
        for (PushConfDO pushConf : pushConfList) {
            String sourceTable = pushConf.getSourceTable() + ReportYearHelper.getStartYear(NumberUtil.parseInt(baseinfo.getAncheyear()));
            if (StrUtil.equals(pushConf.getSourceTable(),"annual_report.t_updateinfo")){
                sourceTable = pushConf.getSourceTable();
            }
            String deleteTemplate = "DELETE FROM {} WHERE ancheid = '{}';";
            String deleteSql = StrUtil.format(deleteTemplate, pushConf.getTargetTable(),baseinfo.getAncheid());
//            jdbcTemplate.update(deleteSql);
            deleteBuilder.append(deleteSql);
            String insertTemplate = "INSERT INTO {} ( {} )SELECT {} FROM {} WHERE ancheid = '{}';";
            String insertSql = StrUtil.format(insertTemplate, pushConf.getTargetTable(), pushConf.getTargetField(), pushConf.getSourceField(), sourceTable,baseinfo.getAncheid());
//            jdbcTemplate.update(insertSql);
            insertBuilder.append(insertSql);
        }
        jdbcTemplate.execute(deleteBuilder.toString());
        jdbcTemplate.execute(insertBuilder.toString());
    }


    private BaseinfoDO getImpBaseInfo(String regno, String impAncheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(impAncheyear));
        LambdaQueryWrapperX<BaseinfoDO> wrapperX = new LambdaQueryWrapperX<>();
        wrapperX.eq(BaseinfoDO::getRegno, regno)
                .eq(BaseinfoDO::getAncheyear, impAncheyear)
                .eq(BaseinfoDO::getState, "02");
        return baseinfoMapper.selectOne(wrapperX);
    }


    private Map<String, Boolean> getFillingResults(String regno, String ancheyear, String enttype) {
        Map<String, Boolean> result = new HashMap<>();
        String ancheid = IdGenerateUtil.getAncheid(regno, ancheyear);
        String config = "";
        BaseinfoDO baseinfo = getBaseinfo(regno, ancheyear);
        Map<String, Object> baseinfoMap = BeanUtil.beanToMap(baseinfo, false, true);
        SupBaseinfoDO supBaseinfo = supBaseinfoService.getSupBaseinfo(regno, ancheyear);
        Map<String, Object> supBaseinfoMap = BeanUtil.beanToMap(supBaseinfo, false, true);
        if (CollUtil.isNotEmpty(supBaseinfoMap)){
            baseinfoMap.putAll(supBaseinfoMap);
        }
        String antype = enttypeAntypeService.getAntype(enttype);
        String configKey = "";
        switch (antype) {
            case "10":
            case "20":
                configKey = "standard.publicMain";
                break;
            case "11":
            case "21":
                configKey = "standard.privateMain";
                break;
            case "30":
                configKey = "standard.publicBranch";
                break;
            case "31":
                configKey = "standard.privateBranch";
                break;
        }
        if (StrUtil.equals(enttype, "9600")) {
            configKey = "standard.individual";
        } else if (StrUtil.equals(enttype, "9100")) {
            configKey = "standard.farmer";
        }
        config = ConfigUtils.getConfigByKey(configKey);
        JSONObject configObj = JSONUtil.parseObj(config);
        Map<String, Object> objectMapMap = BeanUtil.beanToMap(configObj);
        objectMapMap.forEach((key, value) ->
                {
                    result.put(key, true);
                    String val = StrUtil.toString(value);
                    List<String> split = StrUtil.split(val, ',');
                    if (!split.stream().allMatch(baseinfoMap::containsKey)) {
                        result.put(key, false);
                    }
                    if (key.equals("partybuilding") && baseinfo.getPartybuilding().equals("2")) {
                        result.put(key, true);
                    }
                }
        );
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        List<WebsiteinfoDO> websiteinfoList = websiteinfoMapper.selectListByAncheid(ancheid);
        if (baseinfo.getWebsitsign().equals("1") && !websiteinfoList.isEmpty()) {
            result.put("websiteinfo", true);
        } else if (baseinfo.getWebsitsign().equals("2") && websiteinfoList.isEmpty()) {
            result.put("websiteinfo", true);
        }
        List<ForguaranteeinfoDO> forguaranteeinfoList = forguaranteeinfoMapper.selectListByAncheid(ancheid);
        if (StrUtil.equals(baseinfo.getGuaranteesign(),"1") && !forguaranteeinfoList.isEmpty()) {
            result.put("forguaranteeinfo", true);
        } else if (StrUtil.equals(baseinfo.getGuaranteesign(),"2") && forguaranteeinfoList.isEmpty()) {
            result.put("forguaranteeinfo", true);
        }
        List<ForinvestmentDO> forinvestmentList = forinvestmentMapper.selectListByAncheid(ancheid);
        if (StrUtil.equals(baseinfo.getForinvestsign(),"1") && !forinvestmentList.isEmpty()) {
            result.put("forinvestment", true);
        } else if (StrUtil.equals(baseinfo.getForinvestsign(),"2") && forinvestmentList.isEmpty()) {
            result.put("forinvestment", true);
        }
        List<AlterstockinfoDO> alterstockinfoList = alterstockinfoMapper.selectListByAncheid(ancheid);
        if (StrUtil.equals(baseinfo.getStocktransign(),"1") && !alterstockinfoList.isEmpty()) {
            result.put("alterstockinfo", true);
        } else if (StrUtil.equals(baseinfo.getStocktransign(),"2") && alterstockinfoList.isEmpty()) {
            result.put("alterstockinfo", true);
        }
        List<OverduepayDO> overduepayList = overduepayMapper.selectListByAncheid(ancheid);
        if (!overduepayList.isEmpty()){
            OverduepayDO overduepayDO = overduepayList.get(0);
            if (StrUtil.equals(overduepayDO.getIsodsmepay(),"0")){
                result.put("overduepay",true);
            } else if (StrUtil.equals(overduepayDO.getIsodsmepay(), "1")) {
                if(!BeanUtil.hasNullField(overduepayDO)){
                    result.put("overduepay",true);
                }else {
                    result.put("overduepay",false);
                }
            }
        }
        // TODO 获取需要填写的行政许可信息的企业注册号
        //如果当前企业在那个列表里，就未false
        if(true){
            result.put("sfcLicenceinfo", true);
        }
        return result;
    }

    @Override
    public void updateState(String regno, String ancheyear) {
        ReportYearHelper.setYear(NumberUtil.parseInt(ancheyear));
        BaseinfoDO baseinfo = getBaseinfo(regno, ancheyear);
        if (ObjectUtil.isNotEmpty(baseinfo)){
            if (StrUtil.equals(baseinfo.getState(),"02")){
                baseinfo.setState("03");
                baseinfoMapper.updateById(baseinfo);
            }
        }
    }
}

